﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion
{
    /// <summary>
    /// Allows you to iterate through a NotifiableCollection while items are being added and removed from it.
    /// Note: Any items that are added before or during the current index of the iterator will not be retrieved through that iteration. I hope that makes sense! 
    /// </summary>
    public class DynamicIterator<T>
    {
        public int CurrentIndex { get; private set; }
        public bool HasMore { get { return CurrentIndex < notifiableCollection.Count; } }

        private NotifiableCollection<T> notifiableCollection;

        public DynamicIterator() { }
        public DynamicIterator(NotifiableCollection<T> notifiableCollection)
        {
            RegisterCollection(notifiableCollection);
        }

        public void Dispose()
        {
            UnregisterCollection();
        }

        public T Next()
        {
            return notifiableCollection[CurrentIndex++];
        }

        public void Restart()
        {
            CurrentIndex = 0;
        }

        public void RegisterCollection(NotifiableCollection<T> notifiableCollection)
        {
            UnregisterCollection();

            this.notifiableCollection = notifiableCollection;

            if (this.notifiableCollection != null)
                this.notifiableCollection.Removed += new Action<T, int>(NotifiableCollection_Removed);

            CurrentIndex = 0;
        }

        public void UnregisterCollection()
        {
            if (notifiableCollection != null)
            {
                notifiableCollection.Removed -= new Action<T, int>(NotifiableCollection_Removed);
                notifiableCollection = null;
            }
        }

        private void NotifiableCollection_Removed(T removedItem, int removedIndex)
        {
            if (removedIndex < CurrentIndex)
                CurrentIndex -= 1;
        }
    }
}
